import React, { PureComponent } from 'react'
import { connect } from '@umijs/max'
import { Button, message, notification, Steps } from 'antd'
import { DataDevLogger, Loading } from '@/components'
import Tools from '@/utils/Tools'
import { DataSource, DataTarget, FieldMap, SynConfig } from './page-components'
import styles from './index.less'

const { Step } = Steps
const Bus = Tools.Bus

@connect(({ offlineWebServiceApiCreate }) => ({ ...offlineWebServiceApiCreate }))
class WebServiceApiCreateOffline extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      currentStep: 0,
      sourceFormValue: {},
      targetFormValue: {},
      synFormValue: {},
      fieldMapValue: [],
      formData: {},
      showCompSta: false,
      loggerList: [],
      activeKey: '0',
      resultss: [
        {
          result: '运行日志',
          value: ['暂无运行'],
          key: 'logger',
          name: '运行日志',
        },
      ],
      jobId: null,
    }
    this.dataSourceRef = React.createRef()
  }

  UNSAFE_componentWillMount() {
    const { taskNode } = this.props || {}
    const { id } = taskNode
    this.viewDetail(id)
  }

  viewDetail = (idParams) => {
    this.props.dispatch({
      type: 'offlineWebServiceApiCreate/queryGetTaskById',
      params: {
        id: idParams,
      },
      cb: (res) => {
        const { data, status, msg } = res || {}
        if (status === 200) {
          const {
            apiWsRequest, apiHttpRequest, previewExpressRequest, taskName, taskConfigRequest, id, nodeId, nodeName,
          } = data || {}

          if (nodeId) {
            const { fieldMappings } = taskConfigRequest || {}
            const relation = []
            fieldMappings?.map((item) => {
              relation.push({
                source: {
                  fieldName: item.sourceField,
                  fieldType: item.sourceFieldType,
                  isPk: item.isSourceFieldPk,
                  comment: item.comment,
                  key: item.sourceField,
                },
                target: {
                  fieldName: item.targetField,
                  fieldType: item.targetFieldType,
                  isPk: item.isTargetFieldPk,
                  comment: item.comment,
                  key: item.targetField,
                },
              })
              return null
            })

            const formDataTemp = {
              isView: true,
              id,
              nodeId,
              previewExpressRequest,
              taskName,
              relation,
              apiWsRequest: apiWsRequest || apiHttpRequest, // 去掉 apiHttpRequest
              ...taskConfigRequest,
            }

            this.setFormDataFn(formDataTemp)
          } else {
            this.setState({
              showCompSta: true,
            })
          }
        } else {
          this.setState({
            showCompSta: true,
          })
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  // 改变step方法
  changeStep = (stepNum) => {
    this.setState({
      currentStep: stepNum,
    })
  }

  // 运行
  startFlowTask = () => {
    const { taskNode } = this.props || {}
    const { id } = taskNode
    this.props.dispatch({
      type: 'offlineHttpsApiCreate/queryReRunTask',
      params: {
        nodeId: id,
      },
      cb: (res) => {
        const { status, msg, data } = res || {}
        if (status === 200) {
          message.success('操作成功')
          this.setState({
            jobId: data,
          })
          Bus.emit('iconUpFn', this.props?.taskNode?.id)
          this.taskLog(data)
        } else {
          notification.error({
            message: '服务端错误',
            description: msg || '请稍后再试～',
          })
        }
      },
    })
  }

  // 编辑
  handleEditTask = () => {
    this.setState({
      currentStep: 0,
    })

    const formDataTemp = {
      ...this.state.formData,
      isView: false,
    }

    this.setFormDataFn(formDataTemp)
    this.dataSourceRef?.current?.handleToggleAside()
  }

  setFormDataFn = (data) => {
    this.setState({
      formData: data,
      showCompSta: true,
    })
  }

  activeKeyonChange = (activeKey) => {
    this.setState({ activeKey })
  };

  // 任务日志
  taskLog = (jobId, offset) => {
    this.props.dispatch({
      type: 'offlineHttpsApiCreate/queryLog',
      params: {
        jobId,
        offset: offset || offset === 0 ? offset : 0,
      },
      cb: (res) => {
        if (res?.status === 200) {
          clearTimeout(this.time)
          const { logContent, logEnd, results } = res?.data || {}
          const { resultss } = this.state

          let { loggerList } = this.state
          if (logContent && logContent.length) {
            loggerList = loggerList.concat(logContent)
          }
          resultss[0].value = loggerList || []

          const arr = this.state.resultss
          let newResults = [...results]

          if (newResults && newResults.length) {
            newResults.map((obj) => {
              obj.jobId = jobId
            })
            newResults = arr.concat(newResults)
          }

          newResults && newResults.length
            ? newResults.map((item, k) => {
              item.name ? null : (item.name = `结果[${k}]`)
            })
            : null
          this.setState({
            loggerList,
            resultss: newResults && newResults.length ? newResults : arr,
          }, () => {
            this.time = setTimeout(() => {
              this.taskLog(jobId, res.data.offset)
            }, 2000)
          })
          if (logEnd) {
            clearTimeout(this.time)
          }
        } else {
          clearTimeout(this.time)
          message.error(res.msg || '服务端错误')
        }
      },
    })
  }

  // 结束任务
  stopTask = () => {
    const { jobId } = this.state
    this.props.dispatch({
      type: 'offlineHttpsApiCreate/queryStop',
      params: {
        jobId,
      },
      cb: (res) => {
        if (res.status === 200) {
          message.success('操作成功')
          clearTimeout(this.time)
        } else {
          message.error(res.msg || '服务端错误')
        }
      },
    })
  }

  render() {
    const {
      currentStep, sourceFormValue, targetFormValue, synFormValue, fieldMapValue, formData, showCompSta, loggerList, resultss, jobId,
    } = this.state
    const { isView } = formData
    const { taskNode } = this.props
    if (!showCompSta) {
      return (
        <div className={styles.Https_Api_Create}>
          <Loading />
        </div>
      )
    }

    return (
      <div className={styles.Https_Api_Create}>
        {
          isView && (
            <div className={styles.back_bar}>
              <dl onClick={this.startFlowTask}>
                <dt><i className="iconfont icon-yunhang" /></dt>
                <dd>运行</dd>
              </dl>
              <dl onClick={this.stopTask} className={`${jobId ? '' : styles.disabled}`}>
                <dt><i className="iconfont icon-tingzhi" /></dt>
                <dd>停止</dd>
              </dl>
              <Button onClick={this.handleEditTask}>编辑</Button>
            </div>
          )
        }
        <div className={styles.container}>
          {
            !isView && (
              <Steps size="small" className={styles.step} current={currentStep}>
                <Step title="数据来源" />
                <Step title="数据目标" />
                <Step title="字段映射" />
                {/* <Step title="同步配置" /> */}
              </Steps>
            )
          }

          {
            (currentStep === 0 || isView) && <DataSource
              changeStep={this.changeStep}
              initialValues={sourceFormValue}
              taskNode={taskNode}
              formData={formData}
              setFormDataFn={this.setFormDataFn}
              ref={this.dataSourceRef}
            />
           }
          {
            (currentStep === 1 || isView) && <DataTarget
              changeStep={this.changeStep}
              initialValues={targetFormValue}
              taskNode={taskNode}
              formData={formData}
              setFormDataFn={this.setFormDataFn}
            />
           }
          {
            (currentStep === 2 || isView) && <FieldMap
              changeStep={this.changeStep}
              initialValues={fieldMapValue}
              taskNode={taskNode}
              formData={formData}
              setFormDataFn={this.setFormDataFn}
            />
           }
          {/* {
            (currentStep === 3 || isView) && <SynConfig
              changeStep={this.changeStep}
              initialValues={synFormValue}
              taskNode={taskNode}
              formData={formData}
              setFormDataFn={this.setFormDataFn}
            />
           } */}
        </div>
        {
          isView && (
            <DataDevLogger
              list={loggerList || []}
              jobId={jobId}
              className={styles.flow_log}
              style="flow"
              results={resultss}
              activeKey={this.state.activeKey}
              activeKeyonChange={this.activeKeyonChange}
              taskId={taskNode.id}
            />
          )
        }
      </div>
    )
  }
}

export default WebServiceApiCreateOffline
